<?php

/**
 * This is the model class for table "product".
 *
 * The followings are the available columns in table 'product':
 * @property integer  $id
 * @property integer  $categoryId
 * @property string   $name
 * @property string   $avatar
 * @property integer  $price
 * @property string   $dateCreated
 * @property string   $avatarUpload
 * @property integer  $status
 * @property integer  $home
 * @property integer  $feature
 * @property integer  $rank
 *
 * The followings are the available model relations:
 * @property Category $category
 */
class Contact extends CActiveRecord {

    public $upload;
    const MODELPRODUCT = 1;

    /**
     * Returns the static model of the specified AR class.
     * @param string $className active record class name.
     * @return Product the static model class
     */
    public static function model($className = __CLASS__) {
        return parent::model($className);
    }

    /**
     * @return string the associated database table name
     */
    public function tableName() {
        return 'contacts';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules() {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
            array('title, content, userName, email, phone', 'required'),
            array('email', 'email'),
            array('website', 'url'),
            array('regency, fax, address, website, companyName, status', 'safe'),
            array('upload', 'file', 'types' => 'jpg, gif, png, doc, docx, xls, xlsx, zip, rar, pdf', 'allowEmpty' => TRUE),
            array('title, content, userName, email, phone, regency, fax, address, website, status', 'safe', 'on' => 'search'),
        );
    }

    /**
     * @return array relational rules.
     */
    public function relations() {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
        return array(
            'attachment'=>array(self::HAS_ONE, 'File', 'contentId', 'condition'=>'attachment.contentType='.File::TYPE_CONTACT)
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels() {
        return array(
            'title'=>Yii::t('main', 'Title'),
            'content'=>Yii::t('main', 'Content'),
            'userName'=>Yii::t('main', 'Contact User Name'),
            'email'=>Yii::t('main', 'Email'),
            'phone'=>Yii::t('main', 'Phone'),
            'regency'=>Yii::t('main', 'Regency'),
            'fax'=>Yii::t('main', 'Fax'),
            'address'=>Yii::t('main', 'Address'),
            'website'=>Yii::t('main', 'Website'),
            'upload'=>Yii::t('main', 'File Upload'),
            'status'=>Yii::t('main', 'Status')
        );
    }

    protected function beforeSave() {
        $this->createTime=time();
        return parent::beforeSave();
    }
    
    protected function afterSave() {
        if ($this->upload) {
            $fileModel=new File;
            
            $fileName = $this->upload->name;
            $fol=date('Ymd');
            $uploadFolder = Yii::getPathOfAlias('webroot') . DIRECTORY_SEPARATOR . 'files' . DIRECTORY_SEPARATOR . $fol;
            if (!is_dir($uploadFolder)) {
                mkdir($uploadFolder, 0755, TRUE);
            }
            
            $fileName = preg_replace('/[^\w\._]+/', '_', $fileName);

            // Make sure the fileName is unique but only if chunking is disabled
            if (file_exists($uploadFolder . DIRECTORY_SEPARATOR . $fileName)) {
                $ext = strrpos($fileName, '.');
                $fileName_a = substr($fileName, 0, $ext);
                $fileName_b = substr($fileName, $ext);

                $count = 1;
                while (file_exists($uploadFolder . DIRECTORY_SEPARATOR . $fileName_a . '_' . $count . $fileName_b))
                    $count++;

                $fileName = $fileName_a . '_' . $count . $fileName_b;
            }
            
            $uploadFile = $uploadFolder . DIRECTORY_SEPARATOR . $fileName;
            $this->upload->saveAs($uploadFile); //Upload file thong qua object CUploadedFile
            
            $fileModel->name=$fileName;
            $fileModel->url='files/'.$fol.'/'.$fileName;
            $fileModel->contentId=$this->id;
            $fileModel->contentType=  File::TYPE_CONTACT;
            $fileModel->createTime=time();
            
            $fileModel->save();
        }
        
        parent::afterSave();
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
     */
    public function search() {
        // Warning: Please modify the following code to remove attributes that
        // should not be searched.

        $criteria = new CDbCriteria;

        $criteria->compare('id', $this->id);
        $criteria->compare('email', $this->email, true);
        $criteria->compare('phone', $this->phone, TRUE);
        $criteria->compare('title', $this->title, TRUE);
        $criteria->compare('userName', $this->userName, TRUE);
        $criteria->compare('status', $this->status);

        return new CActiveDataProvider($this, array(
                    'criteria' => $criteria,
                    'sort' => array(
                        'defaultOrder' => 'id DESC'
                    ),
                    'pagination' => array(
                        'pageSize' => 20,
                    ),
                ));
    }
    
    protected function afterDelete() {
        if($this->attachment){
            $this->attachment->delete();
        }
        
        parent::afterDelete();
    }

}